package com.stylefeng.guns.modular.system.task;

import java.net.URL;

import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.core.util.HttpClientUtil;
import com.stylefeng.guns.modular.system.constants.ImportContants;
import com.stylefeng.guns.modular.system.dao.GpRemarkMapper;
import com.stylefeng.guns.modular.system.model.GpRemark;

@Service
public class GpRemarkImportTask{

	private Logger log = LoggerFactory.getLogger(GpRemarkImportTask.class);
	
	private static final HttpClientUtil clientUtil = new HttpClientUtil();

	@Autowired
	private GpRemarkMapper gpRemarkMapper;

	public void execute(boolean isHoliday) {
		if(isHoliday){
			String url = ImportContants.getRemarkPathStr(DateUtil.getMMDDTime());
			HttpGet httpGet = HttpClientUtil.getGetRequest();
			try {
				httpGet.setURI(new URL(url).toURI());
				String json = clientUtil.executeAndGetWithFailedRetry(httpGet, 6,10001);
				JSONObject jsonObj = JSON.parseObject(json);
				if(jsonObj.getString("msg").equals("succ")){
					String date = jsonObj.getJSONObject("data").getString("day");
					JSONArray jsonArray = jsonObj.getJSONObject("data").getJSONObject("stock_list").getJSONArray("list");
					for(int i=0;i<jsonArray.size();i++){
						JSONArray jsonArray2 = (JSONArray) jsonArray.get(i);
						String scode = ((JSONObject)jsonArray2.get(0)).getJSONObject("param").getString("code");
						//String name = ((JSONObject)jsonArray2.get(2)).getString("text");
						String text = ((JSONObject)jsonArray2.get(3)).getString("text");
						
						GpRemark gpRemark = new GpRemark();
						gpRemark.setgScode(scode);
						gpRemark.setgDate(DateUtil.parseDate(DateUtil.strToDateFormat(date)));
						
						gpRemark = gpRemarkMapper.selectByDate(gpRemark);
						if(gpRemark == null){
							gpRemark = new GpRemark();
							gpRemark.setgScode(scode);
							gpRemark.setgDate(DateUtil.parseDate(DateUtil.strToDateFormat(date)));
							gpRemark.setgRemark(text);
							gpRemarkMapper.insert(gpRemark);
						}
					}
				}
			} catch (Exception e) {
				log.error("get remark data is error!" + e);
			}finally{
				httpGet.abort();
			}
		}
	}
}